//
//  OYHomePictureView.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/6.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit
import SDWebImage

let OYHomepictureViewCellIdentifier = "OYHomepictureViewCellIdentifier"


let itemMargin:CGFloat = 5
let itemWidth = (ScreenWidth - 2 * (itemMargin + StatusItemMargin)) / 3
let itemHeight = itemWidth

class OYHomePictureView: UICollectionView {

    let flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    var picUrls: [OYStatusPictureModel]? {
        didSet {
            
//            countLabel.text = "\(picUrls?.count ?? 0)"
            
            calcuteViewSize(count: picUrls?.count ?? 0)

            reloadData()
        }
    }
    
     // MARK: -控件懒加载
    lazy var countLabel: UILabel = {
        let label = UILabel()
        return label
    }()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        
        setupUI()
    }
    
    func setupUI() {
        self.backgroundColor = UIColor.init(white: 0.95, alpha: 1)
        
        dataSource = self
        self.register(OYPictureCell.self, forCellWithReuseIdentifier: OYHomepictureViewCellIdentifier)
        
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints(closure: { (make) in
            make.center.equalTo(self)
        })
    }

    func calcuteViewSize (count:Int) {
        
        if count == 1 {
            // 如果图片只有一张，对图片进行缓存，显示图片本身的尺寸
            let urlStr = picUrls?.first?.thumbnail_pic!
           
            if let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: urlStr) {
                var imageSize = image.size
                
                if imageSize.width < 80 {
                    imageSize.height = imageSize.width  / 80 * imageSize.height
                }
                
                if imageSize.height > 150 {
                    imageSize.height = 150
                }
                
                self.snp_updateConstraints(closure: { (make) in
                    make.size.equalTo(imageSize)
                })
                
                
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = imageSize
                
                self.layoutIfNeeded()
            }
           
          
            
            
            return
        }
       
        
        // 根据图片的数目确定view的宽度和高度
        let column = count > 3 ? 3 : count
        let row = (count -  1) / 3 + 1
        
        let viewWidth = CGFloat(column) * itemWidth + CGFloat(column - 1) * itemMargin
        let viewHeight = CGFloat(row) * itemHeight + CGFloat(row - 1) * itemMargin 
        
        
        // 设置view的size
        let viewSize = CGSize(width: viewWidth, height: viewHeight)
        
        // 更新view的约束
        self.snp_updateConstraints { (make) in
            make.size.equalTo(viewSize)
        }
        
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        
        self.layoutIfNeeded()
        
        
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
}

extension OYHomePictureView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OYHomepictureViewCellIdentifier, for: indexPath) as! OYPictureCell
        
        cell.backgroundColor = UIColor.red
        cell.picUrlModel = picUrls![indexPath.item]
        
        return cell
    }
}


 // MARK: -pictureView 的cell
class OYPictureCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
     // MARK: -控件懒加载
    lazy var pictureView:UIImageView = {
        let pictureView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        pictureView.contentMode  = .scaleAspectFill
        pictureView.clipsToBounds = true
        return pictureView
    }()
    
     // MARK: -cell动态添加数据
    var picUrlModel:OYStatusPictureModel? {
        didSet {
            
            
            if let imgUrl = picUrlModel?.thumbnail_pic {
                pictureView.sd_setImage(with: URL(string:imgUrl), placeholderImage: UIImage(named:"timeline_image_placeholder"))
            }
        }
    }
    
    
    func setupUI() {
        
        contentView.addSubview(pictureView)
        
        pictureView.snp_makeConstraints(closure: { (make) in
            make.edges.equalTo(contentView)
        })
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
